package com.eva.ss;

import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import com.eva.framework.rbac.model.RbacUserInfo;
import com.eva.framework.security.utils.SecurityUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 自定义身份认证
 * 身份认证包括密码比对、账户是否过期、账户是否锁定、账户是否可用等层面的处理。
 * 认证失败时将被SystemLoginBiz.login方法捕获并处理
 */
public class DefaultDaoAuthenticationProvider extends DaoAuthenticationProvider {

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            throw new BusinessException(ResponseStatus.ACCOUNT_INCORRECT);
        }
        // 获取需认证的用户信息
        RbacUserInfo loginUserInfo = (RbacUserInfo) userDetails;
        // 密码不一致
        String password = authentication.getCredentials().toString();
        if (!SecurityUtil.encryptPassword(password, loginUserInfo.getSalt()).equals(loginUserInfo.getPassword())) {
            throw new BusinessException(ResponseStatus.ACCOUNT_INCORRECT);
        }
    }
}
